//
//  MMGPrizeClawOpenGLView.m
//  MyApp
//
//  Created by Don on 2017/8/24.
//
//

#import "MMGPrizeClawOpenGLView.h"
#include <OpenGLES/ES2/gl.h>
#include <OpenGLES/ES2/glext.h>

#include "glrenderer.h"

@interface MMGPrizeClawOpenGLView () {
    EAGLContext                 *_context;
    GLuint                      _framebuffer;
    GLuint                      _renderbuffer;
    GLint                       _backingWidth; // UIView width
    GLint                       _backingHeight; // UIView height
    
    CVideoRenderer              *videoRender;
}

@property (nonatomic, strong)UIActivityIndicatorView *videoLoadingView;
@property (nonatomic, assign) CGFloat scaleFactory;
@end
@implementation MMGPrizeClawOpenGLView

+ (Class)layerClass {
    return [CAEAGLLayer class];
}


- (void)dealloc {
    
    if (self) {
        [self tearDownBuffers];
    }
    DLog(@"%@ dealloc", NSStringFromClass([self class]));
}
- (EAGLContext *)createRenderBuffers {
    CAEAGLLayer *glLayer = (CAEAGLLayer *)self.layer;
    glLayer.opaque = YES;//因为缺省的话，CALayer是透明的。而透明的层对性能负荷很大，特别是OpenGL的层
    glLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking,
                                  kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat,
                                  nil];
    
    
    CGFloat scale = [[UIScreen mainScreen] scale];
    if (scale < 0.1f)
        scale = 1.0f;
    
    [glLayer setContentsScale:scale];
    
    EAGLRenderingAPI rendingAPI = kEAGLRenderingAPIOpenGLES2;
    _context = [[EAGLContext alloc] initWithAPI:rendingAPI];
    if (!_context ||
        ![EAGLContext setCurrentContext:_context]) {
        
        DLog(@"failed to setup EAGLContext\n");
    }
    //渲染缓存区绑定
    glGenRenderbuffers(1, &_renderbuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, _renderbuffer);
    [_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer];
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &_backingWidth);
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &_backingHeight);
    
    glGenFramebuffers(1, &_framebuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _renderbuffer);
    
    
    
    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        
        DLog(@"failed to make complete framebuffer object %x\n", status);
    }
    self.scaleFactory = scale;
    
    if (videoRender == NULL) {
        videoRender =new CVideoRenderer();
        //        videoRender->setRenderGLContent(_context);
    }
    
    return _context;
}

- (void)tearDownBuffers {
    
    if (videoRender) {
        delete videoRender;
        videoRender = NULL;
    }
    
    if (_framebuffer) {
        //delete framebuffer
        glDeleteFramebuffers(1, &_framebuffer);
        _framebuffer = 0;
    }
    
    if (_renderbuffer) {
        //delete  render buffer
        glDeleteRenderbuffers(1, &_renderbuffer);
        _renderbuffer = 0;
    }
    
    if ([EAGLContext currentContext] == _context) {
        [EAGLContext setCurrentContext:nil];
    }
    _context = nil;
    
}

- (void)renderGLWithFrame:(uint8_t *)frame
               videoWidth:(float)vWidth
              videoHeight:(float)vHeight
              screenWidth:(float)sWidth screenHeight:(float)sHeight {
    
    if (!_context) {
        return;
    }
    
    videoRender->renderFrame(_context,vWidth, vHeight, sWidth*self.scaleFactory, sHeight*self.scaleFactory, frame);//renderer_renderframe(frame);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (!self.videoLoadingView.isAnimating) {
            return ;
        }
        [self.videoLoadingView stopAnimating];
    });
    
}
//- (void)renderGLWithFrame:(uint8_t *)frame {
//
//    videoRender->renderFrame(, <#int video_height#>, <#int screen_width#>, <#int screen_height#>, frame);//renderer_renderframe(frame);
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if (!self.videoLoadingView.isAnimating) {
//            return ;
//        }
//        [self.videoLoadingView stopAnimating];
//    });
//
//}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self tearDownBuffers];
    //TODO: -此处如果不根据当前glview视图大小生成缓存区长宽，正常比例下渲染会被压扁。
    //获取缓存区大小， glViewPort必须根据此缓存区大小渲染，不然会变形（压扁）
    EAGLContext *currentContent = [self createRenderBuffers];
    if (currentContent ) {
        [self.glContentCreateSignal sendNext:currentContent];
    }
    
    [self.videoLoadingView startAnimating];
    [self.videoLoadingView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self);
        make.left.right.mas_equalTo(self);
        make.top.bottom.mas_equalTo(self);
    }];
}

#pragma mark - lazy init
- (UIActivityIndicatorView *)videoLoadingView {
    if (!_videoLoadingView) {
        _videoLoadingView = [[UIActivityIndicatorView alloc] initWithFrame:self.bounds];
        [_videoLoadingView setUserInteractionEnabled:YES];
        [_videoLoadingView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
        //        [_loadingView setColor:[UIColor mmg_colorWithHex:kMMGColorHex_MainColor]];
        //CGAffineTransform transform = CGAffineTransformMakeScale(.7f, .7f);
        //_loadingView.transform = transform;

        [self addSubview:_videoLoadingView];
    }

    return _videoLoadingView;
}

- (RACSubject *)glContentCreateSignal {
    if (!_glContentCreateSignal) {
        _glContentCreateSignal = [RACSubject subject];
    }
    return _glContentCreateSignal;
}

@end


